import mpld3
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle, Polygon
from matplotlib.font_manager import FontProperties
from matplotlib.legend import Legend
import matplotlib.patheffects as patheffects


class DataCenterVisualizer:
    def __init__(self, unit_size=0.5):
        self.racks = {}
        self.room_layout = {
            'walls': [],
            'doors': [],
            'ac_units': [],
            'aisles': []
        }
        self.unit_size = unit_size
        self.font = FontProperties(fname='simhei.ttf', size=10)
        self.rack_colors = ['#607D8B', '#455A64', '#37474F']
        self.status_colors = {
            'leased': '#2196F3',  # 蓝色表示已租用
            'available': '#4CAF50',  # 绿色表示可用
            'reserved': '#F44336'  # 黄色表示预留
        }

    def add_wall(self, points, thickness=0.2):
        """添加墙壁"""
        self.room_layout['walls'].append({
            'points': points,
            'thickness': thickness
        })

    def add_door(self, position, width=1, direction='horizontal', height="10"):
        """添加门"""
        self.room_layout['doors'].append({
            'position': position,
            'width': width,
            'direction': direction,
            'height': height
        })

    def add_rack(self, name, position, size=(6, 6), row=1, status='unavailable'):
        """添加机柜"""
        self.racks[name] = {
            'position': position,
            'size': (size[0] * self.unit_size, size[1] * self.unit_size),
            'row': row % len(self.rack_colors),
            'status': status,
            'devices': []
        }

    def plot_layout(self, figsize=(15, 10)):
        """生成机房布局图"""
        fig, ax = plt.subplots(figsize=figsize)

        # 绘制墙壁
        for wall in self.room_layout['walls']:
            xs, ys = zip(*wall['points'])
            ax.plot(xs + (xs[0],), ys + (ys[0],),
                    color='#0D47A1', linewidth=wall['thickness'] * 10, zorder=1)

        # 绘制门
        for door in self.room_layout['doors']:
            x, y = door['position']
            if door['direction'] == 'horizontal':
                ax.text(  # x坐标位置
                    80, 151,  # 倒序计算y坐标
                    f"机房大门",
                    fontproperties=FontProperties(fname='simhei.ttf', size=12, weight='bold'),
                    color='#0D47A1',
                    va='bottom',
                    ha='left',
                    bbox=dict(facecolor='white', alpha=0.2,
                              boxstyle='round,pad=0.1',
                              edgecolor='#BBDEFB',
                              linewidth=1))
                ax.add_patch(Rectangle(
                    (x, y), door['width'], 0.2,
                    facecolor='#FFC107', edgecolor='#FF9800', zorder=2
                ))
            else:
                ax.add_patch(Rectangle(
                    (x, y), 0.2, door['width'],
                    facecolor='#FFC107', edgecolor='#FF9800', zorder=2
                ))
        status_colors = {
            'leased': ('#FFFFFF', '#F5F5F5'),
            'available': ('#4CAF50', '#2E7D32'),
            'reserved': ('#F44336', '#C62828'),
            'offline': ('#9E9E9E', '#616161')
        }

        # 绘制机柜
        for name, rack in self.racks.items():
            x, y = rack['position']
            w, h = rack['size']
            color = self.rack_colors[rack['row']]
            status = rack.get('status')
            # 机柜主体
            facecolor, edgecolor = status_colors.get(status, ('#42A5F5', '#1565C0'))
            ax.add_patch(Rectangle(
                (x, y),
                w, h,  # 使用参数化宽度
                facecolor=facecolor,
                edgecolor=edgecolor,
                linewidth=1.8
            ))

            ax.text(x + w / 2, y + h / 2, name,
                    fontproperties=self.font,
                    color='#333333',
                    ha='center', va='center',
                    bbox=dict(facecolor=facecolor, alpha=0.7, edgecolor=edgecolor),
                    path_effects=[patheffects.withStroke(
                        linewidth=2,
                        foreground="white")])

            # 机柜标签
            # ax.text(x + w/2, y + h/2,name,
            #        ha='center', va='center',
            #        color='black', fontproperties=self.font)

            # U位刻度
            for u in range(1, int(h / self.unit_size) + 1, 10):
                ax.plot([x, x + w], [y + u * self.unit_size, y + u * self.unit_size],
                        color='white', linewidth=0.5, linestyle='--')

        # 添加图例
        def zbtex(x, y, c):
            ax.text(
                x, y,  # 倒序计算y坐标
                c,
                fontproperties=FontProperties(fname='simhei.ttf', size=12, weight='bold'),
                color='#0D47A1',
                va='bottom',
                ha='left',
                bbox=dict(facecolor='white', alpha=0.2,
                          boxstyle='round,pad=0.1',
                          edgecolor='#BBDEFB',
                          linewidth=1))

        zbtex(5, 162, "A排业务")
        zbtex(5, 150, "B排业务")
        zbtex(5, 138, "C排业务")
        zbtex(5, 124, "D排业务")
        zbtex(5, 112, "E排业务")
        zbtex(5, 100, "F排业务")
        zbtex(5, 88, "G排业务")
        zbtex(5, 76, "H排业务")
        zbtex(5, 64, "I排业务")
        zbtex(5, 52, "J排业务")
        zbtex(5, 40, "K排业务")
        zbtex(5, 28, "L排业务")
        zbtex(5, 16, "M排业务")
        zbtex(5, 4, "N排业务")
        #    ax.legend(handles=legend_elements, prop=self.font)
        ax.set_aspect('equal')
        ax.set_axis_off()
        ax.set_title("上地硅谷亮城3A-5F-510机房机柜表", fontproperties=FontProperties(
            fname='simhei.ttf', size=16))

        plt.grid(True, alpha=0.3)
        return fig






class DataCenterVisualizerwj:
    def __init__(self, unit_size=0.5):
        self.racks = {}
        self.room_layout = {
            'walls': [],
            'doors': [],
            'ac_units': [],
            'aisles': []
        }
        self.unit_size = unit_size
        self.font = FontProperties(fname='simhei.ttf', size=10)
        self.rack_colors = ['#607D8B', '#455A64', '#37474F']
        self.status_colors = {
            'leased': '#2196F3',  # 蓝色表示已租用
            'available': '#4CAF50',  # 绿色表示可用
            'reserved': '#F44336'  # 黄色表示预留
        }

    def add_wall(self, points, thickness=0.2):
        """添加墙壁"""
        self.room_layout['walls'].append({
            'points': points,
            'thickness': thickness
        })

    def add_door(self, position, width=1, direction='horizontal', height="10"):
        """添加门"""
        self.room_layout['doors'].append({
            'position': position,
            'width': width,
            'direction': direction,
            'height': height
        })

    def add_rack(self, name, position, size=(6, 6), row=1, status='unavailable'):
        """添加机柜"""
        self.racks[name] = {
            'position': position,
            'size': (size[0] * self.unit_size, size[1] * self.unit_size),
            'row': row % len(self.rack_colors),
            'status': status,
            'devices': []
        }

    def plot_layout(self, figsize=(15, 10)):
        """生成机房布局图"""
        fig, ax = plt.subplots(figsize=figsize)

        # 绘制墙壁
        for wall in self.room_layout['walls']:
            xs, ys = zip(*wall['points'])
            ax.plot(xs + (xs[0],), ys + (ys[0],),
                    color='#0D47A1', linewidth=wall['thickness'] * 10, zorder=1)

        # 绘制门
        for door in self.room_layout['doors']:
            x, y = door['position']
            if door['direction'] == 'horizontal':
                ax.text(  # x坐标位置
                    80, 151,  # 倒序计算y坐标
                    f"机房大门",
                    fontproperties=FontProperties(fname='simhei.ttf', size=12, weight='bold'),
                    color='#0D47A1',
                    va='bottom',
                    ha='left',
                    bbox=dict(facecolor='white', alpha=0.2,
                              boxstyle='round,pad=0.1',
                              edgecolor='#BBDEFB',
                              linewidth=1))
                ax.add_patch(Rectangle(
                    (x, y), door['width'], 0.2,
                    facecolor='#FFC107', edgecolor='#FF9800', zorder=2
                ))
            else:
                ax.add_patch(Rectangle(
                    (x, y), 0.2, door['width'],
                    facecolor='#FFC107', edgecolor='#FF9800', zorder=2
                ))
        status_colors = {
            'leased': ('#FFFFFF', '#F5F5F5'),
            'available': ('#4CAF50', '#2E7D32'),
            'reserved': ('#F44336', '#C62828'),
            'offline': ('#9E9E9E', '#616161')
        }

        # 绘制机柜
        for name, rack in self.racks.items():
            x, y = rack['position']
            w, h = rack['size']
            color = self.rack_colors[rack['row']]
            status = rack.get('status')
            # 机柜主体
            facecolor, edgecolor = status_colors.get(status, ('#42A5F5', '#1565C0'))
            ax.add_patch(Rectangle(
                (x, y),
                w, h,  # 使用参数化宽度
                facecolor=facecolor,
                edgecolor=edgecolor,
                linewidth=1.8
            ))

            ax.text(x + w / 2, y + h / 2, name,
                    fontproperties=self.font,
                    color='#333333',
                    ha='center', va='center',
                    bbox=dict(facecolor=facecolor, alpha=0.7, edgecolor=edgecolor),
                    path_effects=[patheffects.withStroke(
                        linewidth=2,
                        foreground="white")])

            # 机柜标签
            # ax.text(x + w/2, y + h/2,name,
            #        ha='center', va='center',
            #        color='black', fontproperties=self.font)

            # U位刻度
            for u in range(1, int(h / self.unit_size) + 1, 10):
                ax.plot([x, x + w], [y + u * self.unit_size, y + u * self.unit_size],
                        color='white', linewidth=0.5, linestyle='--')

        # 添加图例
        def zbtex(x, y, c):
            ax.text(
                x, y,  # 倒序计算y坐标
                c,
                fontproperties=FontProperties(fname='simhei.ttf', size=12, weight='bold'),
                color='#0D47A1',
                va='bottom',
                ha='left',
                bbox=dict(facecolor='white', alpha=0.2,
                          boxstyle='round,pad=0.1',
                          edgecolor='#BBDEFB',
                          linewidth=1))

        zbtex(5, 162, "A排业务")
        zbtex(5, 150, "B排业务")
        zbtex(5, 138, "C排业务")
        zbtex(5, 124, "D排业务")
        zbtex(5, 112, "E排业务")
        zbtex(5, 100, "F排业务")
        zbtex(5, 88, "G排业务")
        zbtex(5, 76, "H排业务")
        zbtex(5, 64, "I排业务")
        zbtex(5, 52, "J排业务")
        zbtex(5, 40, "K排业务")
        zbtex(5, 28, "L排业务")
        zbtex(5, 16, "M排业务")
        zbtex(5, 4, "N排业务")
        #    ax.legend(handles=legend_elements, prop=self.font)
        ax.set_aspect('equal')
        ax.set_axis_off()
        ax.set_title("望京机房机柜表", fontproperties=FontProperties(
            fname='simhei.ttf', size=16))

        plt.grid(True, alpha=0.3)
        return fig
